package cn.chengpengper.seckill.order.application.place.impl;

import cn.chengpengper.dubbo.interfaces.goods.SeckillGoodsDubboService;
import cn.chengpengper.seckill.common.code.HttpCode;
import cn.chengpengper.seckill.common.exception.SeckillException;
import cn.chengpengper.seckill.common.model.dto.SeckillGoodsDTO;
import cn.chengpengper.seckill.common.model.message.TxMessage;
import cn.chengpengper.seckill.order.application.model.command.SeckillOrderCommand;
import cn.chengpengper.seckill.order.application.place.SeckillPlaceOrderService;
import cn.chengpengper.seckill.order.domain.model.entity.SeckillOrder;
import cn.chengpengper.seckill.order.domain.service.SeckillOrderDomainService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

/**
 * @author chengpeng.hu
 */
@Service
@ConditionalOnProperty(name = "place.order.type", havingValue = "db")
public class SeckillPlaceOrderDbServiceImpl implements SeckillPlaceOrderService {

    @DubboReference(version = "1.0.0")
    private SeckillGoodsDubboService seckillGoodsDubboService;

    @Autowired
    private SeckillOrderDomainService seckillOrderDomainService;

    @Override
    public void saveOrderInTransaction(TxMessage txMessage) {

    }

    @Override
    public Long placeOrder(Long userId, SeckillOrderCommand seckillOrderCommand) {
        // 获取商品
        SeckillGoodsDTO seckillGoods = seckillGoodsDubboService.getSeckillGoods(seckillOrderCommand.getGoodsId(), seckillOrderCommand.getVersion());
        // 检测商品信息
        checkSeckillOrder(seckillOrderCommand, seckillGoods);
        // 扣减库存不成功，则库存不足
        if (!seckillGoodsDubboService.decDbAvailableStock(seckillOrderCommand.getQuantity(), seckillOrderCommand.getGoodsId())) {
            throw new SeckillException(HttpCode.STOCK_LT_ZERO);
        }
        // 构建订单
        SeckillOrder seckillOrder = buildSeckillOrder(userId, seckillOrderCommand, seckillGoods);
        // 保存订单
        seckillOrderDomainService.saveSeckillOrder(seckillOrder);
        return seckillOrder.getId();
    }
}
